﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using WHC.Security.BLL;
using WHC.Security.Entity;
using WHC.OrderWater.Commons;
using WeifenLuo.WinFormsUI.Docking;

namespace WHC.Security.UI
{
    public partial class FrmUser : DockContent
    {
        private User user = new User();
        private string currentID = string.Empty;

        public FrmUser()
        {
            InitializeComponent();
        }

        private void FrmUser_Load(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void RefreshTreeView()
        {
            treeView1.Nodes.Clear();
            treeView1.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;

            List<UserInfo> list = user.GetAll();

            this.cmbManager.Items.Clear();
            this.cmbManager.Items.Add(new CListItem("无", "-1")); 

            foreach (UserInfo info in list)
            {
                this.cmbManager.Items.Add(new CListItem(info.Name, info.ID.ToString()));

                if (info.PID != -1)
                {
                    continue;
                }

                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.Name + "（" + info.FullName + "）";
                item.Tag = info.Name;
                this.treeView1.Nodes.Add(item);
                AddChildNode(list, item);
            }

            Cursor.Current = Cursors.Default;
            treeView1.EndUpdate();
            this.treeView1.ExpandAll();
        }
        private void RefreshOUs(int id)
        {
            this.lvwOU.Items.Clear();
            OU ou = new OU();
            foreach (OUInfo info in ou.GetOUsByUser(id))
            {
                this.lvwOU.Items.Add(info.Name);
            }
        }

        private void RefreshRoles(int id)
        {
            this.lvwRole.Items.Clear();
            Role role = new Role();
            foreach (RoleInfo info in role.GetRolesByUser(id))
            {
                this.lvwRole.Items.Add(info.Name);
            }
        }

        private void AddChildNode(List<UserInfo> list, TreeNode fnode)
        {
            foreach (UserInfo info in list)
            {
                if (info.PID != int.Parse(fnode.Name))
                {
                    continue;
                }
                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.Name + "（" + info.FullName + "）";
                item.Tag = info.Name;
                fnode.Nodes.Add(item);

                AddChildNode(list, item);
            }
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeNode node = treeView1.GetNodeAt(e.X, e.Y);
                if (node != null)
                {
                    treeView1.SelectedNode = node;
                }
            }

            base.OnMouseDown(e);
        }

        private void menu_Delete_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && !string.IsNullOrEmpty(node.Name))
            {
                if ("admin".Equals(node.Tag.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    MessageUtil.ShowWarning("保留帐号不能删除");
                    return;
                }

                if (MessageUtil.ShowYesNoAndTips("您确认删除吗?") == DialogResult.Yes)
                {                    
                    try
                    {
                        user.Delete(node.Name);
                        RefreshTreeView();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex);
                        MessageUtil.ShowError(ex.Message);
                    }
                }
            }
        }

        private void menu_Add_Click(object sender, EventArgs e)
        {
            ClearInput();
            currentID = "";
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && node.Tag != null)
            {
                int index = this.cmbManager.FindString(node.Tag.ToString());
                this.cmbManager.SelectedIndex = index;
            }
            this.txtLoginName.Focus();
        }

        private void menu_Function_Click(object sender, EventArgs e)
        {
            FrmEditTree dlg = new FrmEditTree();
            dlg.UserID = currentID;
            dlg.DisplayType = FrmEditTree.DisplayTreeType.Function;
            dlg.btnOK.Enabled = false;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                //RefreshFunctions(Convert.ToInt32(currentID));
            }
        }

        private void menu_Update_Click(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void menu_ExpandAll_Click(object sender, EventArgs e)
        {
            this.treeView1.ExpandAll();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                int id = Convert.ToInt32(e.Node.Name);
                UserInfo info = (UserInfo)user.FindByID(e.Node.Name);

                if (info != null)
                {
                    currentID = id.ToString();
                    RefreshOUs(id);
                    RefreshRoles(id);

                    //如果是管理员，不能设置为过期
                    bool isAdmin = user.UserInRole(info.Name, "管理员");
                    this.chkIsExpired.Enabled = !isAdmin;

                    UserInfo manager = user.FindByID(info.PID.ToString()) as UserInfo;
                    if (manager != null)
                    {
                        this.cmbManager.Text = manager.Name;
                    }
                    else
                    {
                        this.cmbManager.Text = "无";
                    }

                    this.txtAddress.Text = info.Address;
                    this.txtEmail.Text = info.Email;
                    this.txtFullName.Text = info.FullName;
                    this.txtHomePhone.Text = info.HomePhone;
                    this.txtIDNumber.Text = info.IdentityCard;
                    this.txtLoginName.Text = info.Name;
                    this.txtMobile.Text = info.MobilePhone;
                    this.txtPassword.Text = "";
                    this.txtRePass.Text = "";
                    this.txtWorkPhone.Text = info.OfficePhone;
                    this.txtRank.Text = info.Title;
                    this.chkIsExpired.Checked = info.IsExpire;
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            #region 验证用户输入
            if (this.txtLoginName.Text == "")
            {
                MessageUtil.ShowTips("用户名不能为空");
                this.txtLoginName.Focus();
                return;
            }
            else if (this.txtFullName.Text == "")
            {
                MessageUtil.ShowTips("真实姓名不能为空");
                this.txtFullName.Focus();
                return;
            }
            else if (this.txtPassword.Text != this.txtRePass.Text)
            {
                MessageUtil.ShowTips("两次输入的密码不一致");
                this.txtPassword.Focus();
                return;
            }

            if (currentID == "" && this.txtPassword.Text == "")
            {
                MessageUtil.ShowTips("用户密码不能为空");
                this.txtFullName.Focus();
                return;
            }

            #endregion

            if (!string.IsNullOrEmpty(currentID))
            {
                try
                {
                    UserInfo info = user.FindByID(currentID) as UserInfo;
                    if (info != null)
                    {
                        info = SetUserInfo(info);
                        user.Update(info, info.ID.ToString());
                        RefreshTreeView();

                        MessageUtil.ShowTips("资料保存成功");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
            else
            {
                UserInfo info = user.GetUserByName(this.txtLoginName.Text);
                if (info != null)
                {
                    MessageUtil.ShowTips("用户名已存在，或用户名为系统保留！");
                    this.txtLoginName.Focus();
                    return;
                }

                try
                {
                    info = new UserInfo();
                    info = SetUserInfo(info);
                    user.Insert(info);

                    RefreshTreeView();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                }
            }
        }

        private void ClearInput()
        {
            this.txtAddress.Text = "";
            this.txtEmail.Text = "";
            this.txtFullName.Text = "";
            this.txtHomePhone.Text = "";
            this.txtIDNumber.Text = "";
            this.txtLoginName.Text = "";
            this.txtMobile.Text = "";
            this.txtPassword.Text = "";
            this.txtRePass.Text = "";
            this.txtWorkPhone.Text = "";
            this.txtRank.Text = "";
            this.cmbManager.SelectedIndex = 0;

            this.lvwOU.Items.Clear();
            this.lvwRole.Items.Clear();
        }

        private UserInfo SetUserInfo(UserInfo info)
        {
            CListItem item = this.cmbManager.SelectedItem as CListItem;
            if (item != null)
            {
                if (!"admin".Equals(info.Name, StringComparison.OrdinalIgnoreCase))
                {
                    info.PID = int.Parse(item.Value);
                }
            }
            info.Name = this.txtLoginName.Text;
            info.FullName = this.txtFullName.Text;
            info.Address = this.txtAddress.Text;
            info.Email = this.txtEmail.Text;
            info.HomePhone = this.txtHomePhone.Text;
            info.IdentityCard = this.txtIDNumber.Text;
            info.MobilePhone = this.txtMobile.Text;
            info.OfficePhone = this.txtWorkPhone.Text;
            if (currentID == "" || this.txtPassword.Text != "")
            {
                info.Password = this.txtPassword.Text;
            }
            info.Title = this.txtRank.Text;
            info.IsExpire = this.chkIsExpired.Checked;

            return info;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            menu_Add_Click(null, null);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            menu_Delete_Click(null, null);
        }

        private void btnFunction_Click(object sender, EventArgs e)
        {
            menu_Function_Click(null, null);
        }
    }
}
